package com.techstar.common.utils;


import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.JsonNode;
import com.techstar.common.pojo.InterfaceCollect;
import com.techstar.common.pojo.InterfaceType;
import com.techstar.common.repos.InterfaceCollectRepos;

/**
 * 
 * @author EinIce
 * @description 缓存各个接口的数据接收更新时间
 * @date 2021年8月19日
 */
@Configuration
public class InterfaceUtils {
	
	private static InterfaceCollectRepos interfaceCollectRepos;
	
	private static final String NORMAL = "NORMAL";
	private static final String ERROR = "ERROR";
	private static final String NULL = "NULL";
	
	@Autowired
	public void setVipAutoTypeDao(InterfaceCollectRepos interfaceCollectRepos) {
		InterfaceUtils.interfaceCollectRepos = interfaceCollectRepos;
	}
    
    public static void filtrateDate(InterfaceType e, DateTime d ,JsonNode date) {
    	String state = NORMAL;
    	String judgeDate = "";
    	if(date==null) {
    		state = ERROR;
    	}else {
	    	judgeDate = date.toString().trim();
	    	if("".equals(judgeDate))state = NULL;
	    	if("null".equals(judgeDate)||"{null}".equals(judgeDate)||"[null]".equals(judgeDate))state = NULL;
	    	if("{}".equals(judgeDate))state = NULL;
	    	if("[]".equals(judgeDate))state = NULL;
	    	if("[{}]".equals(judgeDate))state = NULL;
    	}
    	getInterfaceCollect(e,d,state);
    }
    
    public static void getInterfaceCollect(InterfaceType k,DateTime d,String state) {
		InterfaceCollect interfaceCollect = new InterfaceCollect();
		if(state != NORMAL) {
			InterfaceCollect lastinterfaceCollect = interfaceCollectRepos.findById(k.id()).get();
			System.out.println("lastinterfaceCollect = " + lastinterfaceCollect);
			if(lastinterfaceCollect!=null)interfaceCollect.setLastUpdate(lastinterfaceCollect.getLastUpdate());
		}
		interfaceCollect.setId(k.id());
		interfaceCollect.setName(k.iname());
		interfaceCollect.setType(k.type());
		interfaceCollect.setDescription(k.description());
		interfaceCollect.setClassName(k.getClassName());
		interfaceCollect.setUpdateTime(d);
		interfaceCollect.setApiUrl(k.getApiUrl());
		interfaceCollect.setState(state);
		synchronized (interfaceCollectRepos) {
			interfaceCollectRepos.save(interfaceCollect);
		}
	}
}
